<?php

namespace App\Services\User;


use App\Actions\MessageAction;
use App\Constants\CodeData;
use App\Dao\CityIpDao;
use App\Dao\ClosenessDao;
use App\Dao\FollowActionDao;
use App\Dao\FollowListDao;
use App\Dao\UserDao;
use App\Dao\UserRemarkDao;
use App\Exception\MessageException;
use App\Model\UserRemark;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use function Hyperf\Translation\trans;

class FollowService
{

    /**
     * Note - 我的关注列表，粉丝列表，互粉列表，密友列表
     * DateTime 2024/8/9 18:21
     * User Admin
     * @param $userInfo
     * @param $params
     */
    public function followList($userInfo, $params)
    {
        $uid = $userInfo['id'];
        $action = $params['action'] ?? 'myfans';

        $ip = FunUtil::getClientIp();
        $ipcache = CityIpDao::getInstance()->getProvinceCity($ip, $userInfo);
        $remarks = [];
        if ($userInfo['sex'] == 2) {
            $remarks = UserRemarkDao::getInstance()->getOne($userInfo['id']);
        }
        if ($action == 'myfans') {
            return $this->getMyFans($userInfo, $ipcache, $remarks, $params);
        } else if ($action == 'myidols') {
            return $this->getMyIdols($userInfo, $ipcache, $remarks, $params);
        } else if ($action == 'mutual_user') {
            return $this->getMutualUser($userInfo, $ipcache, $remarks, $params);
        } else if ($action == 'closeness') {
            $page = $params['page'] ?? 1;
            $pagesize = $params['pagesize'] ?? 10;
            $language = $params['language'] ?? 'en';
            //密友
            $closeness = FollowActionDao::getInstance()->showCloseness($uid, $page, $pagesize, $userInfo['sex'], $language);
            // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $closeness, 'concern_time' => time()), '');
            return formatData(['result' => 1, 'msg' => $closeness, 'concern_time' => time()]);
        }

    }


    /**
     * Note - 我的粉丝列表，关注我的
     * DateTime 2024/8/9 18:22
     * User Admin
     * @param $userInfo
     * @param $ipcache
     * @param array $remarks
     */
    private function getMyFans($userInfo, $ipcache, array $remarks, $params)
    {
        $uid = $userInfo['id'];
        $page = $params['page'] ?? 1;
        $pagesize = $params['pagesize'] ?? 10;
        $language = $params['language'] ?? 'en';

        // 关注我的
        $myfans = FollowActionDao::getInstance()->showMyFans($uid, $page, $pagesize, $language);
        // 我的关注
        $ret = FollowListDao::getInstance()->getIdolsCache($uid);

        $uids = array_column($myfans, 'id');
        $tease_arr = UserDao::getInstance()->readTease($uids, $uid);
        $cArr = ClosenessDao::getMyCloseness($uid, $userInfo['sex'], $uids);

        if (!empty($myfans)) {
            $informationLang = trans('information', [], $language);
            $constellationLang = trans('constellation', [], $language);
            foreach ($myfans as &$v) {
                $v['is_tease'] = isset($tease_arr[$v['id']]) ? 1 : 0;
                if (isset($cArr[$v['id']]) && $cArr[$v['id']] > 0) {
                    $v['is_tease'] = 1;
                }
                $v['ext'] = json_decode($v['ext'], true);
                $job = $v['ext']['job'] ?? '';
                if (!empty($job)) {
                    $v['ext']['job'] = $informationLang['job'][$job]['name'] ?? '';
                } else {
                    $v['ext']['job'] = '';
                }
                $constellation = $v['ext']['constellation'] ?? '';
                if (!empty($constellation)) {
                    $v['ext']['constellation'] = $constellationLang[$constellation] ?? '';
                } else {
                    $v['ext']['constellation'] = '';
                }

                // 关注我的（我的粉丝） 是否在 我关注的列表中
                if (in_array($v['id'], $ret)) {
                    $v['is_concern'] = 1; //已关注
                } else {
                    $v['is_concern'] = 0; //可关注 关注TA
                }
                if ($v['user_type'] == 0) {
                    $v['city'] = $v['city'] ?: $v['province'];
                } else {
                    $v['city'] = $ipcache['city'] ?: $ipcache['province'];
                }
                $v['remarks_name'] = !empty($remarks[$v['id']]) ? $remarks[$v['id']]['remarks_name'] : '';

            }
        }
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $myfans, 'concern_time' => time()), '');
        return formatData(['result' => 1, 'msg' => $myfans, 'concern_time' => time()]);
    }


    /**
     * Note - 我关注的
     * DateTime 2024/8/9 19:07
     * User Admin
     * @param $userInfo
     * @param array $ipcache
     * @param array $remarks
     * @param $params
     */
    private function getMyIdols($userInfo, array $ipcache, array $remarks, $params)
    {
        $uid = $userInfo['id'];
        $page = $params['page'] ?? 1;
        $pagesize = $params['pagesize'] ?? 10;
        $language = $params['language'] ?? 'en';

        //我关注的
        $myidols = FollowActionDao::getInstance()->showMyIdols($uid, $page, $pagesize, $language);

        $uids = array_column($myidols, 'id');
        $tease_arr = UserDao::getInstance()->readTease($uids, $uid);
        $cArr = ClosenessDao::getMyCloseness($uid, $userInfo['sex'], $uids);

        if (!empty($myidols)) {
            $informationLang = trans('information', [], $language);
            $constellationLang = trans('constellation', [], $language);
            foreach ($myidols as &$v) {
                $v['is_tease'] = isset($tease_arr[$v['id']]) ? 1 : 0;
                if (isset($cArr[$v['id']]) && $cArr[$v['id']] > 0) {
                    $v['is_tease'] = 1;
                }

                $v['ext'] = json_decode($v['ext'], true);
                $job = $v['ext']['job'] ?? '';
                if (!empty($job)) {
                    $v['ext']['job'] = $informationLang['job'][$job]['name'] ?? '';
                } else {
                    $v['ext']['job'] = '';
                }
                $constellation = $v['ext']['constellation'] ?? '';
                if (!empty($constellation)) {
                    $v['ext']['constellation'] = $constellationLang[$constellation] ?? '';
                } else {
                    $v['ext']['constellation'] = '';
                }

                $v['is_concern'] = 1; //已关注
                if ($v['user_type'] == 0) {
                    $v['city'] = $v['city'] ?: $v['province'];
                } else {
                    $v['city'] = $ipcache['city'] ?: $ipcache['province'];
                }
                $v['remarks_name'] = (!empty($remarks[$v['id']])) ? $remarks[$v['id']]['remarks_name'] : '';
            }
        }
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $myidols, 'concern_time' => time()), '');
        return formatData(['result' => 1, 'msg' => $myidols, 'concern_time' => time()]);

    }


    /**
     * Note - 相互关注的
     * DateTime 2024/8/9 19:22
     * User Admin
     * @param $userInfo
     * @param array $ipcache
     * @param array $remarks
     * @param $params
     */
    private function getMutualUser($userInfo, array $ipcache, array $remarks, $params)
    {
        $uid = $userInfo['id'];
        $page = $params['page'] ?? 1;
        $pagesize = $params['pagesize'] ?? 10;
        $language = $params['language'] ?? 'en';

        // 相互关注的
        $mutualUser = FollowActionDao::getInstance()->showMutualUser($uid, $page, $pagesize, $language);

        $uids = array_column($mutualUser, 'id');
        $tease_arr = UserDao::getInstance()->readTease($uids, $uid);
        $cArr = ClosenessDao::getMyCloseness($uid, $userInfo['sex'], $uids);

        if (!empty($mutualUser)) {
            $informationLang = trans('information', [], $language);
            $constellationLang = trans('constellation', [], $language);
            foreach ($mutualUser as &$v) {
                $v['is_tease'] = isset($tease_arr[$v['id']]) ? 1 : 0;
                if (isset($cArr[$v['id']]) && $cArr[$v['id']] > 0) {
                    $v['is_tease'] = 1;
                }

                $v['ext'] = json_decode($v['ext'], true);
                $job = $v['ext']['job'] ?? '';
                if (!empty($job)) {
                    $v['ext']['job'] = $informationLang['job'][$job]['name'] ?? '';
                } else {
                    $v['ext']['job'] = '';
                }
                $constellation = $v['ext']['constellation'] ?? '';
                if (!empty($constellation)) {
                    $v['ext']['constellation'] = $constellationLang[$constellation] ?? '';
                } else {
                    $v['ext']['constellation'] = '';
                }

                $v['is_concern'] = 1; //已关注
                if ($v['user_type'] == 0) {
                    $v['city'] = $v['city'] ?: $v['province'];
                } else {
                    $v['city'] = $ipcache['city'] ?: $ipcache['province'];
                }
                $v['remarks_name'] = (!empty($remarks[$v['id']])) ? $remarks[$v['id']]['remarks_name'] : '';
            }
        }
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $mutualUser, 'concern_time' => time()), '');
        return formatData(['result' => 1, 'msg' => $mutualUser, 'concern_time' => time()]);
    }


    /**
     * Note - 关注用户与取消关注
     * DateTime 2024/8/12 18:50
     * User Admin
     * @param mixed $user
     * @param array $params
     */
    public function follow(mixed $user, array $params)
    {
        $uid = $user['id'];
        $user_id = $params['user_id'];
        $action = $params['action'] ?? 'concern';
        if ($uid == $user_id) {
            if ($action == 'concern') {
                $desc = '无法关注';
            } else {
                $desc = '无法取消关注';
            }
            // Tool::JSON(\CodeData::NEED_TIPS, '', $desc);
            throw new MessageException($desc, CodeData::NEED_TIPS);
        }
        $followDao = FollowListDao::getInstance();
        $user_ids = explode(",", $user_id);

        // 批量关注用户
        if (count($user_ids) > 1) {
            foreach ($user_ids as $userId) {
                $followDao->concern($uid, $userId);
            }
            $this->reloadUserFollowUids($uid, $user_id);
            return formatData(['result' => 1], 200, CodeData::SUCCESS, '关注成功');
        }

        $res = UserDao::getInstance()->findUserInfoCache($user_id);
        if (empty($res)) {
            throw new MessageException('你访问的用户不存在', CodeData::NEED_TIPS);
        }

        $user_idols_uids = FollowListDao::getInstance()->getIdolsCache($uid, false); //我的偶像集合
        empty($user_idols_uids) && $user_idols_uids = array();
        if ($action == 'concern') {
            if (in_array($user_id, $user_idols_uids)) {
                // $desc = '已经关注TA了';
                // Tool::JSON(\CodeData::SUCCESS, array('result' => 1), $desc);
                throw new MessageException('已经关注TA了', CodeData::NEED_TIPS);
            } else {
                $followDao->concern($uid, $user_id);
                $this->reloadUserFollowUids($uid, $user_id);
                MemcacheClient::getInstance()->delete("fans_show_num_" . $user_id);

                if ($followDao->isConcern($user_id, $uid)) {
                    // 对方已经关注自己了
                    (new MessageAction())->sendAccostMsg($uid, $user_id, '我关注你了哦~', 1, 43);
                } else {
                    (new MessageAction())->sendAccostMsg($uid, $user_id, '我关注你了哦~', 1, 0);

                }
                return formatData(['result' => 1], 200, CodeData::SUCCESS, '关注成功');
            }

        } else if ($action == 'cancel') {
            if (!in_array($user_id, $user_idols_uids)) {
                throw new MessageException('已经取消关注了', CodeData::NEED_TIPS);
            } else {
                //防止频繁关注、取关的操作
                // if(!MemcacheClient::getInstance()->add("cancel_times_".$uid."_".$user_id, 1 ,300)){
                //     MemcacheClient::getInstance()->increment("cancel_times_".$uid."_".$user_id ,1);
                // }
                // if(MemcacheClient::getInstance()->get("cancel_times_".$uid."_".$user_id) > 1){
                //     $desc = '操作太频繁了，请休息一下';
                //     Tool::JSON(\CodeData::NEED_TIPS, '', $desc);
                //     throw new MessageException('您动作太快了，先喝杯茶再来吧', CodeData::NEED_TIPS);
                // }

                $followDao->cancel($uid, $user_id);
                $this->reloadUserFollowUids($uid, $user_id);
                // $desc = '取消关注成功';
                // Tool::JSON(\CodeData::SUCCESS, array('result' => 1), $desc);
                return formatData(['result' => 1], 200, CodeData::SUCCESS, '取消关注成功');
            }
        }
    }

    public function reloadUserFollowUids($uid, $user_id)
    {
        // $followAction, $uid, $user_id;
        FollowListDao::getInstance()->getIdolsCache($uid, false);
        $page = 1; //暂时只清除第一页的缓存
        $instance = MemcacheClient::getInstance();
        $instance->delete("my_idols_" . $uid . "_" . $page);
        $instance->delete("my_fans_" . $user_id . "_" . $page);
        $instance->delete("mutual_user_" . $uid . "_" . $page);

        $instance->delete("user_idols_uids_" . $uid);
        $instance->delete("user_fans_uids_" . $user_id);

        $instance->delete("user_fans_num_" . $uid);
        $instance->delete("user_focus_num_" . $uid);
        $instance->delete("user_mutual_num_" . $uid);

        $instance->delete("user_fans_num_" . $user_id);
        $instance->delete("user_focus_num_" . $user_id);
        $instance->delete("user_mutual_num_" . $user_id);
    }


}